package com.hermes.util.push;  
  
import java.util.ArrayList;  
import java.util.Collection;  
import java.util.HashMap;
import java.util.HashSet;  
import java.util.Iterator;
import java.util.List;  
import java.util.Map;
import java.util.Set;
  
import javax.annotation.Resource;
import javax.servlet.ServletContext;  
import javax.servlet.http.HttpServletRequest;  
  
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;  
import org.directwebremoting.ServerContext;  
import org.directwebremoting.ServerContextFactory;  
import org.directwebremoting.WebContextFactory;  
import org.directwebremoting.proxy.dwr.Util;  

import com.hermes.biz.common.model.message.PostMessageUnitDO;
import com.hermes.biz.manager.usermodelextra.UserModelExtraManager;
import com.hermes.biz.service.message.MessageReceiverService;
import com.hermes.biz.service.message.MessageReceiverServiceImpl;
import com.hermes.biz.sessionCenter.Qsession;
import com.hermes.biz.sessionCenter.SsionManager;
import com.hermes.util.message.MessageTask;
import com.hermes.biz.sessionCenter.Qsession;
/** 
 *  
 *  
 * @author daniel.ydd
 *  
 */  

public class ChatManager {  
  
	@Resource
	UserModelExtraManager userModelExtraManager;
	SsionManager ssionManager;	
	public static Set<String> msgSendUserIdSet = new HashSet<String>();
	public MessageReceiverServiceImpl messageReceiverService;
	
   

	/** 哥搞了一周，郁闷啊 */  

    public static List<User> users = new ArrayList<User>();  
  
    /** 
     * 
     * @param 
     * @param flag 
     * @param request 
     * @return
     */  
    public String updateUsersList(String userid, boolean flag, HttpServletRequest request) {  
        User user = null; 
        //is in set already
        boolean isLoginYet = false;
       // isLoginYet = isLoginYet(userid,getScriptSessions(userid, request));
        //script session Map deal ,so below can delete
        /*
        if(isLoginYet){
        	return null;
        }
        */
        flag = true;
        if (flag) {   
            // use userid as session id
            //user = new User(request.getSession().getId(), username);  
        	//测试：java调用javascript
        	
        	//判断是否已经登录
        	if(msgSendUserIdSet.contains(userid)){
        		return "ok";
        	}
            user = new User(userid);            
            users.add(user);              
            //登陆后注册到
            msgSendUserIdSet.add(userid);
            this.setScriptSessionFlag(user.getUserid());  
        }          
        ServletContext sc = request.getSession().getServletContext();  
        ServerContext sctx = ServerContextFactory.get(sc);
        
       // Collection sessions = sctx.getScriptSessionsByPage("/index.htm");
        ssionManager = new SsionManager();
        Collection sessions = ssionManager.getAllSession().values();
        if(!flag){  
            return null;  
        }  
     
        return "ok";  
    }  
  
    /** 
     *  daniel
     * @param userid 
     */  
    public void setScriptSessionFlag(String userid) {  
        ScriptSession ss = WebContextFactory.get().getScriptSession();
        ss.setAttribute("userid", userid);
       // Util util = new Util(ss); 
      //  util.setValue("msg", "here");
        //WebContextFactory.get().getScriptSession().setAttribute("userid", userid); 
      //sessionManager deal the map 
        Qsession qssion = new Qsession();
        qssion.setSsionEntry(ss);  
        qssion.setUserId(userid);
        ssionManager = new SsionManager();
        ssionManager.addSession(qssion);
        Qsession q =  ssionManager.getAllSession().get(userid);
        ScriptSession sss = q.getSsionEntry();
//      //测试java 调用javascript
//        ScriptBuffer sb = new ScriptBuffer();
//		sb.appendScript("showMessage()");
//		sss.addScript(sb);
        //测试展示消息弹出
        ScriptBuffer sb = new ScriptBuffer();
		sb.appendScript("showMessage('1','6')");
		//sb.appendScript("pushMessage('1','')");
        sss.addScript(sb);
        Util util = new Util(sss); 
        util.setValue("msg", "tt");
        
        //dealAf();
    }  
    public void setScriptSessionFlag1(String userid) {  
        Qsession q =  ssionManager.getAllSession().get(userid);
        ScriptSession sss = q.getSsionEntry();
        Util util = new Util(sss); 
        util.setValue("msg", "tt111");
    } 
    /** 
     * daniel 
     * @param userid 
     * @param request 
     * @return 
     */  
    @SuppressWarnings("unchecked")  
    public ScriptSession getScriptSession(String userid, HttpServletRequest request) {  
        ScriptSession scriptSessions = null;  
        Collection<ScriptSession> sessions = new HashSet<ScriptSession>();  
        MessageTask.request = request;
        sessions.addAll(ServerContextFactory.get(request.getSession().getServletContext())  
                .getScriptSessionsByPage("/index.htm")); 
        
        for (ScriptSession session : sessions) {  
            String xuserid = (String) session.getAttribute("userid");  
            if (xuserid != null && xuserid.equals(userid)) {  
                scriptSessions = session;  
            }  
        }  
        for (ScriptSession session : sessions) {  
            String xuserid = (String) session.getAttribute("userid");  
            if (xuserid != null && xuserid.equals(userid)) {  
                scriptSessions = session;  
                msgSendUserIdSet.add(userid);
            }  
        }
        //dealAf();
        return scriptSessions;  
    }  
      
    private boolean isLoginYet(String userid,List<ScriptSession> ssSet){
    	for(ScriptSession sess : ssSet){
    		if(sess.getAttribute("userid").equals(userid)){
    			return true;
    		}
    	}
    	return false;
    }
    //登陆，发布等的后续操作
    public void dealAf(ScriptSession session){
    	for(String userid : msgSendUserIdSet){    		
            Qsession q =  ssionManager.getAllSession().get(userid);
            ScriptSession sss = q.getSsionEntry();
            Map<Long,PostMessageUnitDO> pushDestMap = new HashMap<Long,PostMessageUnitDO>();
            messageReceiverService = new MessageReceiverServiceImpl();
            messageReceiverService.init();
            pushDestMap = messageReceiverService.getPostMessageInfo();
            if(pushDestMap.size()<1){
            	return;
            }
            //遍历MAP发送消息
            Set<Long> lkeys = pushDestMap.keySet();
            for(Long lkey : lkeys){            	
            	if(lkey == Long.parseLong(userid)){
            		PostMessageUnitDO msgDO = pushDestMap.get(lkey);
            		int reply = msgDO.getReply();
            		int comm = msgDO.getComment();
            		int fans = msgDO.getFans();
            		String msgSend = String.valueOf(reply)+"-"+String.valueOf(comm)+"-"+String.valueOf(fans);
//            		Util util = new Util(sss);            		
//            		util.setValue("msg", msgSend);
            		//发送消息后，触发推送
            		if(reply!=0){
            			ScriptBuffer sb = new ScriptBuffer();
            			sb.appendScript("showMessage('1','"+fans+"')");;
            			//sb.appendScript("pushMessage('1','')");
            			session.addScript(sb);
            		}
            		if(comm!=0){
            			ScriptBuffer sb = new ScriptBuffer();
            			sb.appendScript("showMessage('2','"+comm+"')");
            			//sb.appendScript("pushMessage('1','')");
            			session.addScript(sb);
            		}
            		if(fans!=0){
            			ScriptBuffer sb = new ScriptBuffer();
            			sb.appendScript("showMessage('1','6')");
            			//sb.appendScript("pushMessage('1','')");
            			session.addScript(sb);
            		}
            	} 
            }            
    	}
    }
    @SuppressWarnings({ "unchecked", "deprecation" })  
    public List<ScriptSession> getScriptSessions(String userid, HttpServletRequest request) {  
        List<ScriptSession> scriptSessionss = new ArrayList<ScriptSession>();  
        Collection<ScriptSession> sessions = new HashSet<ScriptSession>();  
        MessageTask.request = request;
        sessions.addAll(ServerContextFactory.get(request.getSession().getServletContext())  
                .getScriptSessionsByPage("/index.htm")); 
        
        for (ScriptSession session : sessions) {  
           // String xuserid = (String) session.getAttribute("userid");  
            //if (xuserid != null && xuserid.equals(userid)) {  
                scriptSessionss.add(session);
                Util util = new Util(session); 
                util.setValue("msg", "here");                
            //}  
        }  
        
        return scriptSessionss;  
    }  
    
    /** 
     *  daniel
     * @param
     * @param receiverid 
     * @param msg 
     * @param request 
     */  
    @SuppressWarnings("deprecation")
	public void send(String sender,String userid,String msg,HttpServletRequest request){  
       // ScriptSession session = this.getScriptSession(receiverid, request);  
    	List<ScriptSession> sessions = this.getScriptSessions(userid, request);
    	for(ScriptSession session : sessions){
    		Util util = new Util(session); 
    		String id=(String) session.getAttribute("userid");
    		//send message to fans
    		Set<String> fans = new HashSet<String>();
    		fans = getFans(userid);
    		for(String fansId : fans){
    			if(fansId.equals(userid)){
        			util.setValue("msg", msg);
        			dealAf(session);
        		}
    		}    		
    	}
    }  
    
    private Set<String> getFans(String userid){
    	long Luserid = Long.valueOf(userid);
    	Set<String> fanSet = new HashSet<String>();
    	fanSet = userModelExtraManager.getFansIdsMap(Luserid);
    	return fanSet;
    }
    
    //geter setters
    public SsionManager getSsionManager() {
		return ssionManager;
	}

	public void setSsionManager(SsionManager ssionManager) {
		this.ssionManager = ssionManager;
	}
	public MessageReceiverServiceImpl getMessageReceiverService() {
		return messageReceiverService;
	}

	public void setMessageReceiverService(
			MessageReceiverServiceImpl messageReceiverService) {
		this.messageReceiverService = messageReceiverService;
	}
}  